import { useOptimistic, useState } from "react";

// 模拟耗时的网络请求操作
const updateName = async (newName) =>
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(newName);
    }, 5000);
  });

const UpdateNameByReact18 = ({ currentName }) => {
  const [name, setName] = useState(currentName);

  const submitAction = async (formData) => {
    console.log("数据已经被提交，正在请求API");
    const newName = formData.get("name");
    setName(newName); // 虽然立即设置了新的用户名，但并不能立即渲染UI
    const updatedName = await updateName(newName); // 耗时的网络请求
    console.log("网络请求返回的结果是：", updatedName);
  };

  return (
    <form action={submitAction}>
      <p>Your name is {name} (虽然立即设置了新的用户名，但并不能立即渲染UI)</p>
      <p>
        <label>Change Name:</label>
        <input type="text" name="name" disabled={currentName !== name} />
      </p>
      <p>
        <button type="submit">Submit</button>
      </p>
    </form>
  );
};

const UpdateName = ({ currentName }) => {
  const [name, setName] = useState(currentName);
  const [optimisticName, setOptimisticName] = useOptimistic(
    name,
    (state, newState) => `${newState} 正在被提交中，请稍候...`
  );
  const submitAction = async (formData) => {
    console.log("数据已经被提交，正在请求API");
    const newName = formData.get("name");
    setName(newName); // 虽然立即设置了，但是当前的进程需要异步操作结束再继续
    setOptimisticName(newName); // 不等待异步操作，直接更新渲染
    const updatedName = await updateName(newName); // 耗时的网络请求
    console.log("网络请求返回的结果是：", updatedName);

  };

  return (
    <form action={submitAction}>
      <p>optimisticName: {optimisticName} | name: {name}</p>
      <p>
        <label>Change Name:</label>
        <input type="text" name="name" disabled={currentName !== name} />
      </p>
      <p>
        <button type="submit">Submit</button>
      </p>
    </form>
  );
};

export default UpdateName